import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, useResponseSuccess, useResponseError } from '~/utils/response';
import { queryDatabase } from '~/functions';

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }

  const data = await readBody(event); // 读取请求体中的数据
  const dateValue = new Date(data.datePicker.replace('Z', ''));
  const queryString = `
    INSERT INTO bmi (name, height, weight, clothingSize, shoeSize, BMI, BMIStatus, date) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  `;
  const args = [
    data.name,
    data.height,
    data.weight,
    data.clothingSize,
    data.shoeSize,
    parseFloat(data.BMI),
    data.BMIStatus,
    dateValue,
  ];

  // 调用 queryDatabase 函数执行插入操作
  // 插入成功：return useResponseSuccess;
  // 插入失败：return useResponseError;
  try {
    // 调用 queryDatabase 函数执行插入操作
    await queryDatabase(queryString, args);
    return useResponseSuccess({ message: '数据保存成功' });
  } catch (error) {
    return useResponseError(error.message);
  }
});
